import json

from flask import g
from playhouse.shortcuts import model_to_dict

from models.erp import ErpCustomer
from models.sdn import Tenant, Vll, LogicPort
from models.user import Permission, User, UserRole, UserRolePermission, UserOrg, UserLog
from utils.token import make_token
from components.base_exception import PasswordError, NotFoundError
from components.base_log import log_method_call
from components.memcache.connector import cache


@log_method_call(action='Retrieve')
def get_menu_info(parent_id=None):
    permissions = Permission.select().where(Permission.type << [1, 2], Permission.parent_id == parent_id)
    result = []
    for permission in permissions:
        menu = {'name': permission.name, 'id': permission.id}
        children = get_menu_info(permission.id)
        if children:
            menu['child'] = children
        result.append(menu)
    return result


@log_method_call(action='Retrieve')
def get_org_info(user_id):
    data = {'items': []}
    orgs = UserOrg.select().where(UserOrg.user_id == user_id)
    for org in orgs:
        data['items'].append(org.org.get_standard_obj())
    return data


@log_method_call(action='Retrieve')
def get_user_permission(user_id):
    permission_list = []
    user_role = UserRole.get_or_none(UserRole.user_id == user_id, UserRole.is_del == False)
    permissions = UserRolePermission.select().where(UserRolePermission.role == user_role.role)
    for permission in permissions:
        if permission.permission.enable and permission.permission.code:
            permission_list.append(permission.permission.code)
    return permission_list

    # permission_list = []
    # user_roles = UserRole.select().where(UserRole.user_id == user_id)
    # for user_role in user_roles:
    #     permissions = UserRolePermission.select().where(UserRolePermission.role == user_role.role)
    #     for permission in permissions:
    #         if permission.permission.enable and permission.permission.code:
    #             if permission.permission.code not in permission_list:
    #                 permission_list.append(permission.permission.code)
    # return permission_list


@log_method_call(action='Retrieve')
def handel_cache(user_id, type=None):
    permission_list = get_user_permission(user_id)
    # 1.查到当前user.id涉及到的org_id
    # 2.查到涉及到的org_id,对应的所有user1org.id
    users = UserOrg.select().where(UserOrg.user_id == user_id)
    customers = (Tenant
                 .select(Tenant.id)
                 .join(ErpCustomer, on=(Tenant.erp_cust_id == ErpCustomer.cust_id))
                 .where(ErpCustomer.xx_org_id << [user.org_id for user in users]))
    org_ids = [str(customer.id) for customer in customers]
    erps = ErpCustomer.select(ErpCustomer.cust_id).where(ErpCustomer.xx_org_id << [user.org_id for user in users])
    erp_ids = [i.cust_id for i in erps]
    info = {
        "permission": permission_list,
        "id": user_id,
        "org_ids": org_ids,
        "real_org_ids": [user.org_id for user in users],
        'erp_ids': erp_ids
    }
    token = make_token(user_id)
    cache.set(token.encode('utf-8'), json.dumps(info), time=3600)
    UserLog.create(
        type='login',
        user_id=user_id,
        source=type,
        params=''
    )
    vll = Vll.select().where(Vll.tenant_id << org_ids, Vll.is_del == False)
    lgs = LogicPort.select().where(LogicPort.tenant_id << org_ids, LogicPort.is_del == False)
    is_show = False
    if vll or lgs:
        is_show = True
    return {'token': token, 'is_show': is_show}
